package kr.co.cherryt.view;

import kr.co.cherryt.cherryt.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.view.View;

public class PlayerProgressBar extends View {
	Context mContext;
	int mMax;
	int mPos;
	Bitmap mBackgroundBmp = null;
	Bitmap mForegroundBmp = null;

	public PlayerProgressBar(Context context) {
		super(context);
		mContext = context;
		init();
	}

	public PlayerProgressBar(Context context, AttributeSet attrs) {
		super(context, attrs);
		mContext = context;
		init();
	}

	public PlayerProgressBar(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		mContext = context;
		init();
	}

	void init() {
		mMax = 100;
		mPos = 0;
		mBackgroundBmp = BitmapFactory.decodeResource( mContext.getResources(), R.drawable.movie_bar_background );
		mForegroundBmp = BitmapFactory.decodeResource( mContext.getResources(), R.drawable.movie_bar_foreground );
	}

	void setMax(int nMax) {
		mMax = nMax;
	}

	int getMax() {
		return mMax;
	}

	public void setProgress(int nPos) {
		if(nPos<0 || nPos>mMax) return;

		mPos = nPos;
		invalidate();
	}

	int getPos() { return mPos; }

	protected void onDraw(Canvas canvas) {
		Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);

		int w = getWidth();
		
		Rect src = new Rect(0, 0, mBackgroundBmp.getWidth(), mBackgroundBmp.getHeight());
		Rect dst = new Rect();
		dst.left = 10;
		dst.top = 0;
		dst.right = w;
		dst.bottom = mBackgroundBmp.getHeight();
		canvas.drawBitmap( mBackgroundBmp, src, dst, paint );

		src = new Rect(0, 0, mForegroundBmp.getWidth(), mForegroundBmp.getHeight());
		dst = new Rect();
		dst.left = 10;
		dst.top = 0;
		dst.right = mPos * w / mMax;
		dst.bottom = mForegroundBmp.getHeight();
		canvas.drawBitmap(mForegroundBmp, src, dst, paint);
	}

	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		int nWidth = 460;
		int nHeight = 20;

		switch( MeasureSpec.getMode(widthMeasureSpec) )
		{
		case MeasureSpec.AT_MOST:
			nWidth = Math.min(MeasureSpec.getSize(widthMeasureSpec), nWidth);
			break;
		case MeasureSpec.EXACTLY:
			nWidth = MeasureSpec.getSize(widthMeasureSpec);
			break;
		}

		switch( MeasureSpec.getMode(heightMeasureSpec) )
		{
		case MeasureSpec.AT_MOST:
			nHeight = Math.min(MeasureSpec.getSize(heightMeasureSpec), nHeight);
			break;

		case MeasureSpec.EXACTLY:
			nHeight = MeasureSpec.getSize(heightMeasureSpec);
			break;
		}

		setMeasuredDimension(nWidth, nHeight);
	}
}
